﻿using System.Collections.Generic;
using System.Text.RegularExpressions;

namespace MobileBank1
{
	public class RecordReader
	{
		public FileReader MyFileReader { get; set; }
		public Regex RecordHeadeRegex = new Regex(UsefulResource.HeaderPattern, RegexOptions.IgnoreCase | RegexOptions.Singleline);

		private string _temporaryHead;

		public RecordReader(FileReader myFileReader)
		{
			MyFileReader = myFileReader;
		}

		public List<string> GetRecord()
		{
			var result = new List<string>();

			var headerString = string.IsNullOrEmpty(_temporaryHead) ? FindRecordHeader() : _temporaryHead;

			result.Add(headerString);

			if (string.IsNullOrEmpty(headerString))
				return result;

			List<string> body;
			_temporaryHead = GetRecordBody(out body);
			result.AddRange(body);

			return result;
		}

		private string FindRecordHeader()
		{
			var temString = MyFileReader.GetNextString();
			var found = false;

			while (!RecordHeadeRegex.IsMatch(temString))
			{
				found = true;
				temString = MyFileReader.GetNextString();
			}

			return found ? temString : null;
		}

		private string GetRecordBody(out List<string> recordBody)
		{
			recordBody = new List<string>();

			var temString = MyFileReader.GetNextString();
			while (!RecordHeadeRegex.IsMatch(temString))
			{
				recordBody.Add(temString);
				temString = MyFileReader.GetNextString();
			}

			return temString;
		} 
	}
}
